﻿using BPipeline.Runtime.RenderPass;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Experimental.Rendering.RenderGraphModule;
using UnityEngine.Rendering;

namespace BPipeline.Runtime
{
    [CreateAssetMenu(menuName = "BRenderPipeline/BRenderPieplineAsset")]
    public class BRenderPipelineAsset : RenderPipelineAsset
    {
        protected override RenderPipeline CreatePipeline()
        {
            return new BRenderPipeline();
        }
    }

    public class BRenderPipeline : RenderPipeline
    {
        RenderGraph mRenderGraph;

        int frameIdx = 0;
        
        
        public BRenderPipeline()
        {
            mRenderGraph = new RenderGraph("BRenderPipeline");
            
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            mRenderGraph.Cleanup();
            mRenderGraph = null;
        }
        class BlitPassData
        {
            public bool flipY;
            public TextureHandle inputSrc;
            public TextureHandle indst;
            public TextureHandle dst;
        }

        class SkyPassData
        {
            public TextureHandle inputTex;
            public TextureHandle outputTex;
        }
        
        protected override void Render(ScriptableRenderContext context, Camera[] cameras)
        {
            BeginFrameRendering(context,cameras);
            foreach (var camera in cameras)
            {
                BeginCameraRendering(context,camera);

                var cmd = CommandBufferPool.Get("RG" + camera);
                RenderGraphParameters renderGraphParameters = new RenderGraphParameters()
                {
                    scriptableRenderContext = context,
                    commandBuffer = cmd,
                    currentFrameIndex = frameIdx++
                };

                camera.TryGetCullingParameters(out var cullingParameters);
                var cullResults =  context.Cull(ref cullingParameters);
                using (mRenderGraph.RecordAndExecute(renderGraphParameters))
                {
                    var  gBufferPassData=  GBufferPass.Excute(mRenderGraph, camera);
                    PresentPass.Excute(mRenderGraph, camera, gBufferPassData.gBufferPosWR);
                }

                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);

                context.Submit();
                EndCameraRendering(context,camera);
            }
            mRenderGraph.EndFrame();
            EndFrameRendering(context,cameras);
        }
    }
}
